# !/usr/bin/env python3
# -*- coding: utf-8 -*-

from lib.tsn_builder_lib import host_to_net
import xml.etree.ElementTree as EleTree
from tsn_builder_struct.para_simple_tbl_structure import ParaSimTbl, ParaSimTblEachNode


def link_para_sim_tbl(para_tbl,
                      reg_addr):
    dic = []

    tbl_each_node = para_tbl.tbl_each_node
    addr8 = reg_addr.schedule_period['addr']
    addr8_str = host_to_net(addr8)
    value8 = tbl_each_node.byte.entry8
    value8_str = host_to_net(value8)
    addr_value = {'addr': addr8_str,
                  'value': [value8_str]}
    dic.append(addr_value)

    addr9 = reg_addr.cycle_start_cyclen['addr']
    addr9_str = host_to_net(addr9)
    value9 = tbl_each_node.byte.entry9
    value9_str = host_to_net(value9)
    addr_value = {'addr': addr9_str,
                  'value': [value9_str]}
    dic.append(addr_value)

    addr10 = reg_addr.time_slot_len['addr']
    addr10_str = host_to_net(addr10)
    value10 = tbl_each_node.byte.entry10
    value10_str = host_to_net(value10)
    addr_value = {'addr': addr10_str,
                  'value': [value10_str]}
    dic.append(addr_value)

    return dic


def _get_para_sim_tbl(para_tbl_xml):
    para_set = []

    root = EleTree.parse(para_tbl_xml)
    node_ele_set = root.findall('node')
    for node_ele in node_ele_set:
        para_dic = {}
        node_type = int(node_ele.findtext('node_type'))
        if node_type == 2 or node_type == 3:  # 传感器 测试仪
            node_id = node_ele.findtext('node_id')
            schedule_period = node_ele.findtext('schedule_period')
            cyclelen = node_ele.findtext('cyclelen')
            time_slot_len = node_ele.findtext('time_slot_len')
            para_dic.update({'node_id': int(node_id),
                             'src_node': int(node_id),
                             'node_type': node_type,
                             'schedule_period': int(schedule_period),
                             'cyclelen': int(cyclelen),
                             'time_slot_len': int(time_slot_len)})
            para_set.append(para_dic)
    return para_set


def _init_para_sim_tbl(para_set):
    para_tbl = ParaSimTbl()
    for entry_each_node in para_set:
        para_tbl_each_node = ParaSimTblEachNode(**entry_each_node)
        para_tbl.append_tbl(para_tbl_each_node)

    return para_tbl


def read_para_sim_tbl(para_tbl_xml):
    para_set = _get_para_sim_tbl(para_tbl_xml)
    # [print(entry) for entry in para_set]
    para_tbl = _init_para_sim_tbl(para_set)
    return para_tbl


def main():
    para_tbl_xml = '../output/tbl/para_tbl.xml'
    read_para_sim_tbl(para_tbl_xml)


if __name__ == '__main__':
    main()
